<?php
class Gallery extends Controller
{
	public function _construct()
	{
		fw::lang('gallery');
	}
	
	public function view($alpha)
	{
		// Get ID
		$index = 'bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ';
		
		$base = strlen($index);

		$in  = strrev($alpha);
		$out = 0;
		$len = strlen($in) - 1;

		for($t=0; $t<=$len; $t++)
		{
			$bcpow = bcpow($base, $len - $t);
			
			$out = $out + strpos($index, substr($in, $t, 1)) * $bcpow;
		}

		$out = sprintf('%F', $out);

		$id = substr($out, 0, strpos($out, '.'));
		
		// Image
		$image = new Image($id);
		
		if($image->id)
		{
			$image->views++;
			
			// HTTP
			$http = 'http://'.$_SERVER['HTTP_HOST'].WEB;
			
			// Gallery
			$format = fw::get_cookie('format', 'gallery/%s/%s/%d/');
			$place = (int) fw::get_cookie('place', 0);
			$order = fw::get_cookie('order', 'new');
			$range = fw::get_cookie('range', 'all');
			$page = fw::get_cookie('page', 1);
			
			if($place && !db::num_rows(db::query('SELECT NULL FROM `'.DB_PREFIX.'User` WHERE `id`='.$place))) $place = 0;
			
			// Slider
			$index = 0;
			
			if($place && $place == User::is_authenticated())
			{
				$query = 'WHERE `private` IS NOT NULL';
			} else
			{
				$query = 'WHERE `private`=0';
			}
			
			if($place) $query .= ' AND `User_id`='.$place;
			
			switch($range)
			{
				case 'month':
					$query .= ' AND `date` > NOW() - INTERVAL 1 MONTH';
					break;
				case 'week':
					$query .= ' AND `date` > NOW() - INTERVAL 1 WEEK';
					break;
				case 'today':
					$query.= ' AND `date` > NOW() - INTERVAL 1 DAY';
					break;
			}
			
			$gallery = new Image($query);
			$total = $gallery->count();
			
			switch($order)
			{
				case 'new':
					$query .= ' ORDER BY `date` DESC';
					break;
				case 'popular':
					$query .= ' ORDER BY `views` DESC';
					break;
			}
			
			// Get index
			$result = db::query('SELECT `id` FROM `'.DB_PREFIX.'Image` '.$query);
			while($row = db::fetch($result, 'row'))
			{
				if($row[0] == $image->id) break;
				
				$index++;
			}
			
			$galleries = array();
			
			$min = $index - 2;
			$max = $index + 2;
			
			if($total <= 5)
			{
				$galleries[] = new Image($query);
			} else
			{
				if($min < 0)
				{
					$galleries[] = new Image($query.' LIMIT '.($total + $min).',5');
					$galleries[] = new Image($query.' LIMIT 0,'.(5 + $min));
					
					$min = $total + $min;
				} else
				{
					$galleries[] = new Image($query.' LIMIT '.$min.',5');
					
					if($max >= $total)
					{
						$galleries[] = new Image($query.' LIMIT 0,'.($max - $total + 1));
					}
				}
				
				Template::script_var('INDEX', $min);
			}
			
			// Delete
			if(isset($_POST['delete']) && User::is_authenticated() && (User::is_authenticated() == $image->User_id || User::is_admin()))
			{
				$image->delete();
				
				header('Location: '.WEB.sprintf($format, $order, $range, $page));
				
				exit();
			}
			
			// Template
			Template::script('jquery', 'view');
			
			define('PATH', WEB);
			
			Template::script_var('WEB', WEB);
			Template::script_var('PATH', PATH);
			Template::script_var('PLACE', $place);
			Template::script_var('ORDER', $order);
			Template::script_var('RANGE', $range);
			Template::script_var('CURRENT', $image->id);
			
			require Template::render('Gallery', 'view.html');
		} else
		{
			Template::meta('refresh', '3;'.WEB);
			
			require Template::render('Gallery', 'not_found.html');
		}
	}
	
	private function images($query, $order, $range, $page, $format, $user_id=0, $username=null)
	{
		// Check
		$month = db::fetch(db::query('SELECT COUNT(*) FROM `'.DB_PREFIX.'Image` WHERE '.$query.' AND `date` > NOW() - INTERVAL 1 MONTH'), 'row');

		if(!$month[0])
		{
			$week = array(0);
			$today = array(0);
		} else
		{
			$week = db::fetch(db::query('SELECT COUNT(*) FROM `'.DB_PREFIX.'Image` WHERE '.$query.' AND `date` > NOW() - INTERVAL 1 WEEK'), 'row');
			
			if(!$week[0])
			{
				$today = array(0);
			} else
			{
				$today = db::fetch(db::query('SELECT COUNT(*) FROM `'.DB_PREFIX.'Image` WHERE '.$query.' AND `date` > NOW() - INTERVAL 1 DAY'), 'row');
			}
		}
		
		// Gallery
		$images = new Image('WHERE '.$query);
		
		// Range
		switch($range)
		{
			case 'month':
				if($month[0])	$images->query('AND `date` > NOW() - INTERVAL 1 MONTH');
				break;
			case 'week':
				if($week[0])	$images->query('AND `date` > NOW() - INTERVAL 1 WEEK');
				break;
			case 'today':
				if($today[0])	$images->query('AND `date` > NOW() - INTERVAL 1 DAY');
				break;
		}

		if($range !== 'all')
		{
			$check = $$range;
			
			if(!$check[0]) $range = 'all';
		}
		
		// Page
		$total = $images->count();
		$pages = ceil($total/25);
		
		if($page < 1) $page = 1;
		if($page > $pages) $page = $pages;
		
		$min = $page - 4;
		$max = $page + 4;
		
		if($min < 1)
		{
			$max += 1 - $min;
			$min = 1;
		}
		
		if($max > $pages)
		{
			$min += $pages - $max;
			
			if($min < 1) $min = 1;
			
			$max = $pages;
		}
		
		// Order
		switch($order)
		{
			case 'new':
				$images->query('ORDER BY `date` DESC');
				break;
			case 'popular':
				$images->query('ORDER BY `views` DESC');
				break;
		}
		
		$images->query('LIMIT '.($page*25-25).',25');
		
		// Cookies
		fw::set_cookie('format', $format);
		fw::set_cookie('place', $user_id);
		fw::set_cookie('range', $range);
		fw::set_cookie('order', $order);
		fw::set_cookie('page', $page);
		
		// Header
		$title = $user_id?lang('images_of', array('name'=>$username)):lang('gallery');
		
		// Template
		require Template::render('Gallery', 'browse.html');
	}
	
	public function user($username, $order='new', $range='all', $page=1)
	{
		if($row = db::fetch(db::query('SELECT `id` FROM `'.DB_PREFIX.'User` WHERE `username`="'.db::escape($username).'"'), 'row'))
		{
			if(User::is_authenticated() == $row[0])
			{
				$query = '`private` IS NOT NULL AND `User_id`='.$row[0];
			} else
			{
				$query = '`private`=0 AND `User_id`='.$row[0];
			}
			
			$this->images($query, $order, $range, $page, 'user/'.$username.'/%s/%s/%d/', $row[0], $username);
		}
	}
	
	public function browse($order='new', $range='all', $page=1)
	{
		$this->images('`private`=0', $order, $range, $page, 'gallery/%s/%s/%d/');
	}
}